package com.zlm.design.decorator;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zlm
 * @date 2025/4/18
 */
public class BufferedFileInputStream extends InputStream {

    private final byte[] buffer = new byte[8096];

    //读取位置
    private int posstion = -1;
    //内容总长
    private int capacity = -1;

    private final FileInputStream fileInputStream;

    public BufferedFileInputStream(FileInputStream fileInputStream) {
        this.fileInputStream = fileInputStream;
    }

    @Override
    public int read() throws IOException {
        if(buffCanRead()){
            return readFromBuffer();
        }
        refreshBuffer();

        if(!buffCanRead()){
            return -1;
        }
        return readFromBuffer();
    }

    private void refreshBuffer() throws IOException {
        capacity = this.fileInputStream.read(buffer);
        posstion = 0;

    }

    private int readFromBuffer() {
        return buffer[posstion++] & 0xFF;
    }

    private boolean buffCanRead() {
        if(capacity == -1){
            return false;
        }
        if(posstion == capacity){
            return false;
        }
        return true;
    }

    @Override
    public void close() throws IOException {
        super.close();
    }

}
